const express = require('express');
const router = express.Router();
const mysql = require('mysql2/promise');
const dbConfig = require('../config/database');

// 登录
router.post('/login', async (req, res) => {
    try {
        const { email, password } = req.body;
        const connection = await mysql.createConnection(dbConfig);

        const [users] = await connection.execute(
            'SELECT id, name, email FROM users WHERE email = ? AND password = ?',
            [email, password]
        );

        await connection.end();

        if (users.length === 0) {
            return res.status(401).json({ error: '邮箱或密码错误' });
        }

        res.json(users[0]);
    } catch (error) {
        res.status(500).json({ error: '登录失败' });
    }
});

// 注册
router.post('/register', async (req, res) => {
    try {
        const { name, email, phone, password } = req.body;

        // 验证必填字段
        if (!name || !email || !password) {
            return res.status(400).json({ error: '姓名、邮箱和密码为必填项' });
        }

        // 验证邮箱格式
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(email)) {
            return res.status(400).json({ error: '请输入正确的邮箱格式' });
        }

        // 验证密码长度
        if (password.length < 6 || password.length > 20) {
            return res.status(400).json({ error: '密码长度必须在6-20位之间' });
        }

        const connection = await mysql.createConnection(dbConfig);

        // 检查邮箱是否已存在
        const [existing] = await connection.execute(
            'SELECT id FROM users WHERE email = ?',
            [email]
        );

        if (existing.length > 0) {
            await connection.end();
            return res.status(400).json({ error: '该邮箱已被注册' });
        }

        const [result] = await connection.execute(
            'INSERT INTO users (name, email, phone, password) VALUES (?, ?, ?, ?)',
            [name, email, phone, password]
        );

        await connection.end();
        res.status(201).json({
            id: result.insertId,
            name,
            email,
            phone
        });
    } catch (error) {
        console.error('注册失败:', error);
        res.status(500).json({
            error: '注册失败',
            details: error.message
        });
    }
});

// 重置密码
router.post('/reset-password', async (req, res) => {
    try {
        const { email, phone, newPassword } = req.body;

        // 验证必填字段
        if (!email || !phone || !newPassword) {
            return res.status(400).json({ error: '所有字段都是必填的' });
        }

        const connection = await mysql.createConnection(dbConfig);

        // 验证用户身份
        const [users] = await connection.execute(
            'SELECT * FROM users WHERE email = ? AND phone = ?',
            [email, phone]
        );

        if (users.length === 0) {
            await connection.end();
            return res.status(400).json({ error: '邮箱或手机号不正确' });
        }

        // 更新密码
        await connection.execute(
            'UPDATE users SET password = ? WHERE email = ? AND phone = ?',
            [newPassword, email, phone]
        );

        await connection.end();
        res.json({ message: '密码重置成功' });
    } catch (error) {
        console.error('重置密码失败:', error);
        res.status(500).json({
            error: '重置密码失败',
            details: error.message
        });
    }
});

module.exports = router; 